<?php

namespace app\widgets;


use Yii;
use yii\base\Widget;
use yii\helpers\Html;
use yii\helpers\Url;

class ShareWidget extends Widget {

    public $title;
    public $share_url;
    protected $shareButtons = [];

    public function init() {
        parent::init();
        if (empty($this->share_url)) {
            $this->share_url = Url::to([Yii::$app->request->url], TRUE);
        }

        $this->shareButtons = [
            'Twitter' => [
                'icon' => 'icon-twitter', 'url' => Url::to("https://twitter.com/intent/tweet?text={$this->title}&url={$this->share_url}")
            ],
            'Facebook' => [
                'icon' => 'icon-facebook', 'url' => Url::to("https://facebook.com/sharer/sharer.php?t={$this->title}&u={$this->share_url}")
            ],
            'Pinterest' => [
                'icon' => 'icon-pinterest', 'url' => Url::to("https://pinterest.com/pin/create/button/?description={$this->title}&url={$this->share_url}&media={$this->share_url}")
            ],
            'Google' => [
                'icon' => 'icon-google-plus', 'url' => Url::to("https://plus.google.com/share?url={$this->share_url}")
            ],
            'Tumblr' => [
                'icon' => 'icon-tumblr', 'url' => Url::to("https://www.tumblr.com/widgets/share/tool?posttype=link&title={$this->title}&caption={$this->title}&content={$this->share_url}&canonicalUrl={$this->share_url}&shareSource=tumblr_share_button")
            ],
            'Telegram' => [
                'icon' => 'icon-telegram', 'url' => "https://telegram.me/share/url?text={$this->title}&url={$this->share_url}"
            ],
            'Line' => [
                'icon' => 'icon-line', 'url' => "https://social-plugins.line.me/lineit/share?url={$this->share_url}"
            ],
        ];
    }

    public function run() {
        $icon = Html::tag('i', '<span>分享</span>', ['class' => "iconfont icon-share"]);
        $data[] = Html::a($icon, 'javascript:;', ['class' => "btn"]);

        foreach ($this->shareButtons as $name => $button) {
            $icon = Html::tag('i', '', ['class' => "iconfont {$button['icon']}"]);
            $id = strtolower($name);
            $data[] = Html::a($icon, $button['url'], ['class' => "tooltip btn btn-{$id}", 'data-tooltip' => $name, 'target' => '_blank']);
        }

        return join("\n", $data);
    }
}